package com.example.controller;

import java.util.*;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.domain.LoginBO;
import com.example.domain.User;
import com.example.service.UserService;
import com.example.utils.JsonData;
import com.example.utils.String2Map;

import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;





@RestController
@RequestMapping("/login")
public class LoginController {
	

    @Autowired
    private UserService userService;
	
	@Value("${mini.path}")
	private String path;
	
	@Value("${mini.appID}")
	private String appID;
	
	@Value("${mini.AppSecret}")
	private String AppSecret;
	/**
	 * 小程序登录
	 * @throws IOException 
	 */
	@PostMapping
	public Object login(@RequestBody LoginBO loginBO) throws IOException {
		System.out.println(loginBO);
		/**
		 * 获取session_key
		 */
		String url = path + "appid=" + appID + "&secret=" + AppSecret + "&js_code=" + loginBO.getCode() + "&grant_type=authorization_code";
		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder().url(url).build();
		Response response = client.newCall(request).execute();
		Map<String, String> map2 = new HashMap<String, String>();
		if(response.isSuccessful()) {
			String body = response.body().string();
			Map<String, Object> map1 = String2Map.string2map(body);
			String openid =  map1.get("openid").toString();
			String session_key =  map1.get("session_key").toString();
			map2.put("openid", openid);
			User loginUser  = new User();
			List list = new ArrayList<User>();
			list = userService.findAll();
			int a = -1;
			for(User user: (List<User>)list) {
				if(user.getOpenid().equals(openid)) { 
					// 有用户 更新信息
					a = 1;
					User loginUser2  = new User();
					DateFormat dateFormat = new  SimpleDateFormat("yyyy/dd/MM HH:mm:ss");
			    	Date date = new Date();
			    	loginUser2.setCreateTime(date);
			    	loginUser2.setOpenid(openid);
					loginUser2.setSession_key(session_key);
					loginUser2.setAvatarUrl(loginBO.getAvatarUrl());
					loginUser2.setCity(loginBO.getCity());
					loginUser2.setCountry(loginBO.getCountry());
					loginUser2.setGender(loginBO.getGender());
					loginUser2.setLanguage(loginBO.getLanguage());
					loginUser2.setNickName(loginBO.getNickName());
					loginUser.setProvince(loginBO.getProvince());
				}
			}
			if(a != 1) {
				// 无用户 写入用户库
				DateFormat dateFormat = new  SimpleDateFormat("yyyy/dd/MM HH:mm:ss");
		    	Date date = new Date();
		    	loginUser.setCreateTime(date);
		    	loginUser.setOpenid(openid);
				loginUser.setSession_key(session_key);
				loginUser.setAvatarUrl(loginBO.getAvatarUrl());
				loginUser.setCity(loginBO.getCity());
				loginUser.setCountry(loginBO.getCountry());
				loginUser.setGender(loginBO.getGender());
				loginUser.setLanguage(loginBO.getLanguage());
				loginUser.setNickName(loginBO.getNickName());
				loginUser.setProvince(loginBO.getProvince());
		    	System.out.println(dateFormat.format(date));
		    	userService.add(loginUser);
			}
		}
		return JsonData.buildSuccess(map2);
		
	}
}
